package com.nc.delivery_project.client.schedule_details;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

import com.google.web.bindery.requestfactory.shared.Receiver;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.ScheduleRequest;
import com.nc.delivery_project.shared.proxy.CurrencyProxy;
import com.nc.delivery_project.shared.proxy.DepartmentProxy;
import com.nc.delivery_project.shared.proxy.LegalPersonProxy;
import com.nc.delivery_project.shared.proxy.ScheduleProxy;

import java.util.List;


/**
 * Created by DRAGON on 14.01.2015.
 */

public class ScheduleDetailsActivity extends AbstractActivity implements ScheduleDetailsPresenter {


    private ScheduleDetailsView view;

    private ClientFactory clientFactory;

    private ScheduleProxy schedule;

    private int scheduleId;

    private List<DepartmentProxy> departments;
    private List<LegalPersonProxy> legalpersons;
    private List<CurrencyProxy> currencys;

    private ScheduleRequest updateRequest;

    private int fetchedCount;






    public ScheduleDetailsActivity(ScheduleDetailsPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
        parseToken(place.getToken());
        updateRequest = clientFactory.getRequestFactory().createScheduleRequest();

    }
    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        fetchDepartments();
        fetchLegalPersons();
        fetchCurrencys();
        fetchSchedule(scheduleId);

        if (view == null) {
            view = new ScheduleDetailsView();
        }

        view.setPresenter(this);
        panel.setWidget(view);
        view.start();

        view.scheduleIdLbl.setText(String.valueOf(scheduleId));

        initButtonHandlers();
    }


    @Override
    public void loadScheduleDetails(ScheduleProxy schedule) {

        view.scheduleIdLbl.setText(String.valueOf(schedule.getId()));
        view.primeCostTxtBox.setText(String.valueOf(schedule.getPrimeCost()));
        view.sellingRateTxtBox.setText(String.valueOf(schedule.getSellingRate()));
        view.departureDateTxtBox.setText(String.valueOf(schedule.getDepartureDate()));
        view.arrivalDateTxtBox.setText(String.valueOf(schedule.getArrivalDate()));
        view.tariffDateTxtBox.setText(String.valueOf(schedule.getTariffDate()));
    }

    @Override
    public void update(ScheduleProxy schedule) {
        updateRequest.update(schedule).fire();
        Window.Location.reload();
    }
    @Override
    public void fillDepartmentDropBox(List<DepartmentProxy> departments) {
        for (int i = 0; i < departments.size(); i++) {
            DepartmentProxy department = departments.get(i);
            view.originLstBox.addItem(department.getAddress(), String.valueOf(department.getDeptId()));
            view.destinationLstBox.addItem(department.getAddress(), String.valueOf(department.getDeptId()));
            if (department.getDeptId() == schedule.getOrigin().getDeptId())
                view.originLstBox.setItemSelected(i, true);
            if (department.getDeptId() == schedule.getDestination().getDeptId())
                view.destinationLstBox.setItemSelected(i, true);
        }
    }
    @Override
    public void fillLegalPersonDropBox(List<LegalPersonProxy> legalpersons) {
        for (int i = 0; i < legalpersons.size(); i++) {
            LegalPersonProxy legalperson = legalpersons.get(i);
            view.transportCompanyLstBox.addItem(legalperson.getTitle(), String.valueOf(legalperson.getLegalPersonId()));
                if (legalperson.getLegalPersonId() == schedule.getDestination().getDeptId())
                view.destinationLstBox.setItemSelected(i, true);
        }
    }
    @Override
    public void fillCurrencyDropBox(List<CurrencyProxy> currencys) {
        for (int i = 0; i < currencys.size(); i++) {
            CurrencyProxy currency = currencys.get(i);
            view.currencyLstBox.addItem(currency.getTitle(), String.valueOf(currency.getId()));
            if (currency.getId() == schedule.getDestination().getDeptId())
                view.destinationLstBox.setItemSelected(i, true);
        }
    }
    @Override
    public void delete(int scheduleId) {
        clientFactory.getRequestFactory().createScheduleRequest().delete(scheduleId).fire();
    }

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }

    private void initButtonHandlers() {
        view.saveBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                schedule.setOrigin(departments.get(view.originLstBox.getSelectedIndex()));
                schedule.setDestination(departments.get(view.destinationLstBox.getSelectedIndex()));
                schedule.setTransportCompany(legalpersons.get(view.transportCompanyLstBox.getSelectedIndex()));
                schedule.setCurrency(currencys.get(view.currencyLstBox.getSelectedIndex()));
                update(schedule);
            }
        });


        view.removeBtn.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                delete(schedule.getId());
            }
        });
    }
    private void fetchDepartments() {
        clientFactory.getRequestFactory().createDepartmentRequest().read().fire(new Receiver<List<DepartmentProxy>>() {
            @Override
            public void onSuccess(List<DepartmentProxy> response) {
                GWT.log("departments fetched");
                departments = response;

                if (++fetchedCount == 2) fillView();
            }
        });
    }
    private void fetchLegalPersons() {
        clientFactory.getRequestFactory().createLegalPersonRequest().read().fire(new Receiver<List<LegalPersonProxy>>() {
            @Override
            public void onSuccess(List<LegalPersonProxy> response) {
                GWT.log("legalpersons fetched");
                legalpersons = response;

                if (++fetchedCount == 2) fillView();
            }
        });
    }
    private void fetchCurrencys() {
        clientFactory.getRequestFactory().createCurrencyRequest().read().fire(new Receiver<List<CurrencyProxy>>() {
            @Override
            public void onSuccess(List<CurrencyProxy> response) {
                GWT.log("currencys fetched");
                currencys = response;

                if (++fetchedCount == 2) fillView();
            }
        });
    }
    private void fetchSchedule(int id) {
        ScheduleRequest ScheduleRequest = clientFactory.getRequestFactory().createScheduleRequest();

        ScheduleRequest.read(id).with("origin","destination","transportCompany","currency").fire(new Receiver<ScheduleProxy>() {
            @Override
            public void onSuccess(ScheduleProxy response) {
                GWT.log("Schedule fetched");
                schedule = updateRequest.edit(response);

                if (++fetchedCount == 2) fillView();
            }
        });
    }

    private void fillView() {
        fillDepartmentDropBox(departments);
        fillLegalPersonDropBox(legalpersons);
        fillCurrencyDropBox(currencys);
        loadScheduleDetails(schedule);
    }
    private void parseToken(String token) {
        try {
            scheduleId = Integer.parseInt(token);
        } catch (NumberFormatException e) {
            Window.alert("Unknown Token");
        }
    }


}